package server

import (
	"encoding/json"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/gorilla/websocket"
)

func (tis *WebRtcEngine) pushWebsocketConnection(c *gin.Context) {
	var websocketUpGrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	name := c.Param("name")
	log.Println(name)

	conn, err := websocketUpGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}

	ws := &WeSocketWebrtcConnectionPush{
		WeSocketWebrtcConnection: &WeSocketWebrtcConnection{
			UID:  uuid.NewString(),
			Name: name,

			engine: tis,
			ws:     conn,
			pc:     nil,
		},
		receiver: map[string]*WeSocketWebrtcConnectionPull{},
	}

	tis.streamPushListMux.Lock()
	tis.streamPushList[ws.UID] = ws
	tis.streamPushListMux.Unlock()

	defer func() {
		ws.Close()

		tis.streamPushListMux.Lock()
		delete(tis.streamPushList, ws.UID)
		tis.streamPushListMux.Unlock()

		_ = conn.Close()
	}()

	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("recv: %s", message)

		var request JsonProtocol
		if err = json.Unmarshal(message, &request); err != nil {
			continue
		}

		ws.OnRequest(&request)
	}
}

func (tis *WebRtcEngine) pullWebsocketConnection(c *gin.Context) {
	var websocketUpGrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	name := c.Param("name")
	log.Println(name)

	conn, err := websocketUpGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}

	ws := &WeSocketWebrtcConnectionPull{
		WeSocketWebrtcConnection: &WeSocketWebrtcConnection{
			UID:  uuid.NewString(),
			Name: name,

			engine: tis,
			ws:     conn,
			pc:     nil,
		},
	}

	defer func() {
		ws.Close()
		_ = conn.Close()
	}()

	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		// log.Printf("recv: %s", message)

		var request JsonProtocol
		if err = json.Unmarshal(message, &request); err != nil {
			continue
		}

		ws.OnRequest(&request)
	}
}
